<?php

namespace app\admin\controller\draw;

use app\admin\model\Admin;
use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 提成明细
 *
 * @icon fa fa-circle-o
 */
class Drawlog extends Backend
{

    /**
     * Drawlog模型对象
     * @var \app\common\model\draw\Drawlog
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\draw\Drawlog;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $user_id = $this->request->request('user_id');
            $map = !empty($user_id) ? ['user_id' => $user_id] : [];

            $filter = json_decode($this->request->get("filter", ''), true);
            $admin_ids = [];
            if (isset($filter['merchant'])) {
                //自定义处理
                $admin_ids = Admin::where('id|username|nickname', 'like', "%{$filter['merchant']}%")->column('id');
                $op = $filter['merchant'];
                $this->request->get(['filter' => json_encode($op, true)]);
                $this->request->get(['op' => json_encode($op, true)]);

                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            }else{
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            }



            $auth_group_access = \think\Db::name('auth_group_access')->where('uid', $this->auth->id)->find();
            if (empty($auth_group_access)) {
                $merchant = [];
            } elseif ($auth_group_access['group_id'] == 2) {
                if(isset($filter['status']) && $filter['status']==3){
                    $merchant= [];
                }else{
                    $merchant = ['merchant_id' => $this->auth->id];
                }
            } else {
                $merchant = [];
            }
            $where_merchant = [];
            $merchant2 = $this->request->request('merchant_id');
            if ($merchant2) {
                $where_merchant = ['merchant_id' => $merchant2];
            }

            $list = $this->model
                ->where($where)
                ->where($merchant)
                ->where(function ($query) use ($admin_ids) {
                    if(!empty($admin_ids)){
                        return $query->whereIn('merchant_id',$admin_ids);
                    }
                })
                ->where($where_merchant)
                ->where($map)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {
//                $row->getRelation('user')->visible(['nickname']);
//                $row->getRelation('merchant')->visible(['nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }

        $auth_group_access = \think\Db::name('auth_group_access')->where('uid', $this->auth->id)->find();
        if (empty($auth_group_access)) {
            $merchant = [];
        } elseif ($auth_group_access['group_id'] == 2) {
            $merchant = ['merchant_id' => $this->auth->id];
        } else {
            $merchant = [];
        }

        $status1 = $this->model->where($merchant)->where('status', 0)->sum('money');
        $status2 = Admin::where('id', $this->auth->id)->value('money');
        $this->view->assign("money1", $status1);
        $this->view->assign("money2", $status2);
        $this->view->assign("admin_id", $this->auth->id);
        return $this->view->fetch();
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {

            $this->view->assign('row', $row);

            $authGroupList = AuthGroupAccess::where('group_id', 2)->column('uid');
            $list = Admin::where('id', 'in', $authGroupList)
                ->field(['password', 'salt', 'token'], true)
                ->order('id', 'desc')
                ->select();
            $new_array = [];
            $unshift = ['id' => 0, 'username' => '平台会员', 'nickname' => '平台会员',];
            foreach ($list as $key => $value) {
                $new_array[$key] = $value;
            }
            array_unshift($new_array, $unshift);

            $this->view->assign("merchantList", $new_array);

            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');

        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            if ($params['status'] == 1) {
                Admin::where('id', $params['merchant_id'])->setInc('money', $params['money']);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }

        $this->success();
    }

}
